package com.elinkway.infinitemovies.utils;

/**
 * Created by chenliangzhu on 2016/8/10.
 */
public class VersionUtil {

    private static final String VERSION_PATTERN = "\\d+(\\.\\d+){0,2}";
    private static final int MAX_SEGMENTS = 3;

    public static boolean verify(String version) {
        return version != null && version.matches(VERSION_PATTERN);
    }

    public static int[] digitise(String version) {
        if (!verify(version)) {
            throw new IllegalArgumentException();
        }
        int[] dv = new int[MAX_SEGMENTS];
        String[] vns = version.split("\\.");
        for (int i = 0; i < vns.length; i++) {
            dv[i] = Integer.parseInt(vns[i]);
        }
        return dv;
    }

    public static int compare(String v1, String v2) {
        if (!verify(v1) || !verify(v2)) {
            throw new IllegalArgumentException();
        }
        int[] dn1 = digitise(v1);
        int[] dn2 = digitise(v2);
        for (int i = 0; i < MAX_SEGMENTS; i++) {
            if (dn1[i] != dn2[i]) {
                return dn1[i] - dn2[i];
            }
        }
        return 0;
    }
}
